package com.roc.web.action.terminal;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.TermBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblTfrTrnLog;
import com.roc.service.IAgentService;
import com.roc.service.IExcelService;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.ITerminalService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.web.action.OperatorQueryAction;
import com.roc.web.action.agent.AgentStatisticsSearchCondition;
import com.roc.web.action.estrn.EstrnInfoSearchCondition;
@SuppressWarnings("serial")
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/termStatistics")
public class TerminalStatisticsAction extends PaginationBaseAction {
	private Logger logger=LogManager.getLogger(OperatorQueryAction.class);
	private TerminalStatisticsSearchCondition searchCondition;
	private InputStream excelFile;
	private String super_id;//父级代理商 即分公司
	private String directFlag;//直属代理商标志
	private String agentFlag;//所属分公司标志
	private String currentAgentFlag;//子级代理商标志
	private List<Map<String,Object>> listMap;
	private List<TermBean> terminalList=new ArrayList<TermBean>();
	@Autowired 
	private IMerchantServices merchantServices;
	@Autowired
	private ITerminalService terminalService;	
	@Autowired
	IPageService pagenitionService;
	@Autowired
	private IExcelService excelService;
	@Autowired
	private IAgentService agentService;
	@Action(value="initPage",results={@Result(name="success",location="/pages/terminal/terminal_statistics.jsp")
	,@Result(name="error",location="/error.jsp")})
	public String initTermStatics()
	{
		try {
			//权限分配
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		if(logingMerchant.getRoleType().equals(Role.AGENT.getCode()))
		{
			 Map<String,String> map=agentService.queryAgentDirectMap(String.valueOf(logingMerchant.getId()));
			 if(map!=null)
			 {
				 if(map.containsKey("msg"))
				 {
					 addActionError("代理商所属不在收单事业部或子级代理中");
					 return ERROR;
				 }
				 if(map.containsKey("agentId"))
				 {
					 agentFlag="exist";
					 List<Operators> lists=null;
					 if(map.containsKey("flag"))//登录代理商
					 {
						 currentAgentFlag="exist";
					 }
					 lists = new ArrayList<Operators>();
					 Operators op= new Operators();
					 op.setId(Long.valueOf(String.valueOf(map.get("agentId"))));
					 op.setRealName(map.get("agentName"));
					 lists.add(op);
					 getRequest().setAttribute("opList",lists);
				 }
			 }
			 else{
				 org();
			 }
		}
		else if(logingMerchant.getRoleType().equals(Role.SYSTEM.getCode())||logingMerchant.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())||logingMerchant.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode()))
		{
			org();//加载分公司
		}
		else{
			addActionError("无访问权限");
			return ERROR;
		}
			searchCondition = new TerminalStatisticsSearchCondition();
			// 默认查询当天日期
			String today = Constance.currTime();
			searchCondition.setMinDate(today);
			searchCondition.setMaxDate(today);
		} catch (Exception e) {
			addActionError("初始终端统计页面出错!!!");
			e.printStackTrace();
			return ERROR;
		}
		return SUCCESS;
	}
	@Action(value="queryTermStatisticsList",results={@Result(name="success",location="/pages/terminal/terminal_statistics.jsp")
	,@Result(name="error",location="/error.jsp")})
	public String queryTermActList()
	{
		
		try {
		if (searchCondition == null) {
			searchCondition = (TerminalStatisticsSearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new TerminalStatisticsSearchCondition();
			}
		}
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		if(logingMerchant.getRoleType().equals(Role.AGENT.getCode()))
		{
			 Map<String,String> map=agentService.queryAgentDirectMap(String.valueOf(logingMerchant.getId()));
			 if(map!=null)
			 {
				 if(map.containsKey("msg"))
				 {
					 addActionError("代理商所属不在收单事业部或子级代理中");
					 return ERROR;
				 }
				 if(map.containsKey("agentId"))
				 {
					 agentFlag="exist";
					 List<Operators> lists=null;
					 if(map.containsKey("flag"))//登录代理商
					 {
						 currentAgentFlag="exist";
					 }
					 lists = new ArrayList<Operators>();
					 Operators op= new Operators();
					 op.setId(Long.valueOf(String.valueOf(map.get("agentId"))));
					 op.setRealName(map.get("agentName"));
					 lists.add(op);
					 getRequest().setAttribute("opList",lists);
				 }
			 }
			 else{
				 org();
			 }
		}
		else if(logingMerchant.getRoleType().equals(Role.SYSTEM.getCode())||logingMerchant.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())||logingMerchant.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode()))
		{
			directFlag="noExist";
			org();//加载分公司
		}
		else{
			addActionError("无访问权限");
			return ERROR;
		}
			int rows = pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				dealWithTheListSpecially(searchRsList);
			}
			this.setTotalPage(this.calcuTotalPage(rows));
			addActionMessage("当前条件下统计到【"+rows+"】条记录");
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
	@Action(value="excelTermStatisticsList",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xlsx",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/error.jsp") }) 
	public String  exportEstrn() throws Exception{
		
			 Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

			 try {
				 if (searchCondition == null) {
					searchCondition = (TerminalStatisticsSearchCondition) getSearchConditionFromSession();
					if (searchCondition == null) {
						searchCondition = new TerminalStatisticsSearchCondition();
					}
				 }				
				//org();//加载分公司
				int rows = pagenitionService.countSQL(searchCondition);
				if(rows>0){
					searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()),rows);
					dealWithTheListSpecially(searchRsList);
				}
					
					SXSSFWorkbook work=excelService.exportTerminalStaList(terminalList, searchCondition.getMinDate(), searchCondition.getMaxDate(),currentAgentFlag);

					 ByteArrayOutputStream output = new ByteArrayOutputStream();  
					         work.write(output);  
					   
					        byte[] ba = output.toByteArray();  
					         excelFile = new ByteArrayInputStream(ba);  
					         output.flush();  
					         output.close();  
					
		}catch (ServiceException e) {
			e.printStackTrace();
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
			
		}
		
		return SUCCESS;
	}
	// 加载数据
		public void org() throws Exception{
				List<Operators> opList = new ArrayList<Operators>();
				// 收单事业部Id
				String supId = "40001";
				// 查询某个代理商的直属代理商
				opList = merchantServices.queryLowOneAgent(supId);
				getRequest().setAttribute("opList", opList);
			}
		@Action(value = "directAgent",results={@Result(type="json",params={"root","listMap"})})
		public String directAgent()
		{
			if(super_id!=null)
			{
				listMap=terminalService.superAgentId(super_id);
			}
			return SUCCESS;
		}
		
	@Override
	protected void dealWithTheListSpecially(List<Object> list) {
		if(list!=null&&list.size()>0){
			
			Iterator<Object> iterator=list.iterator();
			while(iterator.hasNext())
			{				
				Object[] obj=(Object[]) iterator.next();
				TermBean temp=new TermBean();
				temp.setOrgName(Constance.Null2EmptyTrim(obj[0]));
				temp.setAgentName(Constance.Null2EmptyTrim(obj[1]));
				temp.setMid(Constance.Null2EmptyTrim(obj[2]));
				temp.setTid(Constance.Null2EmptyTrim(obj[3]));
				temp.setSerialNum(Constance.Null2EmptyTrim(obj[4]));
				terminalList.add(temp);
			}
		}
	}
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);

	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_TERMINAL_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_BEAN_TERMINAL_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}
	
	public String getSuper_id() {
		return super_id;
	}
	public void setSuper_id(String super_id) {
		this.super_id = super_id;
	}
	public List<Map<String, Object>> getListMap() {
		return listMap;
	}
	public void setListMap(List<Map<String, Object>> listMap) {
		this.listMap = listMap;
	}
	public TerminalStatisticsSearchCondition getSearchCondition() {
		return searchCondition;
	}
	public void setSearchCondition(TerminalStatisticsSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	public List<TermBean> getTerminalList() {
		return terminalList;
	}
	public void setTerminalList(List<TermBean> terminalList) {
		this.terminalList = terminalList;
	}
	public InputStream getExcelFile() {
		return excelFile;
	}
	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getDirectFlag() {
		return directFlag;
	}
	public void setDirectFlag(String directFlag) {
		this.directFlag = directFlag;
	}
	
	public String getCurrentAgentFlag() {
		return currentAgentFlag;
	}
	public void setCurrentAgentFlag(String currentAgentFlag) {
		this.currentAgentFlag = currentAgentFlag;
	}
	public String getAgentFlag() {
		return agentFlag;
	}
	public void setAgentFlag(String agentFlag) {
		this.agentFlag = agentFlag;
	}
	public String getExcelName() {
		String excelName="终端统计"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		 
		return  excelName;
	}
}
